﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Sbook.AdminIstrator
{
    public partial class Products1 : System.Web.UI.Page
    {
        private static bool Insert = false;
        private static string Id = "";
        private static bool Flag = true;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {

                if (Data.Mysession.isLogin)
                {
                    if (Request.QueryString["p"] == null)
                    {
                        BindListProduct();
                    }
                    else
                    {
                        rpProduct.DataSource = Business.ProductsService.FormatSaleOff(Business.ProductsService.Products_GetByCaId(Request.QueryString["p"]));
                        rpProduct.DataBind();
                    }
                    //if (Flag == false)
                    //    lblMess.Visible = true;
                }
                else
                {
                    Response.Redirect("/AdminIstrator/Login.aspx");
                }
            }
        }
        private void BindListProduct()
        {
            int pageSize = 10; // so san pham tren 1 trang
            int total = 0;
            total = Business.ProductsService.Products_GetByAll().Count;
            int pages = total / pageSize; // so trang
            if (total % pageSize > 0)
                pages++;
            int currentPage = 1; // trang hien tai
            if (Request.QueryString["page"] != null)
            {
                try
                {
                    currentPage = Convert.ToInt32(Request.QueryString["page"]);
                }
                catch
                {
                    Response.Redirect("/AdminIstrator/Products.aspx");
                    currentPage = 1;
                }
            }
            if (currentPage <= 1)
            {
                ltrPaging.Text = "<span class=\"disabled\"><< prev</span>";
            }
            else
            {
                ltrPaging.Text = "<a href=\"/AdminIstrator/Products.aspx?page=" + (currentPage - 1) + "\"><< prev</a>";
            }
            for (int i = 1; i <= pages; i++)
            {
                if ((i > 3) && (currentPage - i > 3 && currentPage - i < 10 || (currentPage - i > 12)) || (i - currentPage > 3 && i - currentPage < 10 || (i - currentPage > 12)) && i < pages - 2)
                {
                    continue;
                }
                if (currentPage == i)
                    ltrPaging.Text += "<span class=\"current\">" + i + "</span>";
                else
                {
                    ltrPaging.Text += "<a href=\"/AdminIstrator/Products.aspx?page=" + i + "\">" + i + "</a>";
                }
            }
            if (currentPage >= pages)
            {
                ltrPaging.Text += "<span class=\"disabled\">next >></span>";
                //Response.Redirect("/AdminIstrator/ListDelivery.aspx?page=4");
            }
            else
            {
                ltrPaging.Text += "<a href=\"/AdminIstrator/Products.aspx?page=" + (currentPage + 1) + "\">next >></a>";
            }
            if (currentPage <= 0)
            {
                currentPage = 1;
                Response.Redirect("/AdminIstrator/Products.aspx");
            }
            rpProduct.DataSource = Business.ProductsService.FomatPrice1(Business.ProductsService.FormatSaleOff(Business.ProductsService.Products_Paging(currentPage.ToString(), pageSize.ToString())));

            rpProduct.DataBind();
        }
        //Load DropDow
        private void LoadDropDown()
        {

            ddlCate.Items.Clear();
            ddlPublish.Items.Clear();
            ddlCate.Items.Add(new ListItem("====Chọn danh mục====", "0"));
            ddlPublish.Items.Add(new ListItem("====Chọn nhà xuất bản=====", "0"));
            List<Data.CategoryInfo> listCat = Business.CategoryService.Category_GetByAll().FindAll(c=>c.cpID!="0");
            List<Data.PublisherInfo> listP = Business.PublisherService.Publisher_GetByAll();
            for (int i = 0; i < listCat.Count; i++)
            {
                ddlCate.Items.Add(new ListItem(listCat[i].cName, listCat[i].cID));
            }
            for (int i = 0; i < listP.Count; i++)
            {
                ddlPublish.Items.Add(new ListItem(listP[i].PName, listP[i].PId));
            }
            ddlPublish.DataBind();
            ddlCate.DataBind();
        }
        private static string PDate = "";
        protected void rptProductCommand(object sender, RepeaterCommandEventArgs e)
        {
            string strCA = e.CommandArgument.ToString();
            switch (e.CommandName)
            {
                case "Edit":
                    Id = strCA;
                    Insert = false;
                    List<Data.ProductsInfo> listU = Business.ProductsService.Products_GetById(Id);
                    LoadDropDown();
                    ddlCate.Text = listU[0].CatId;
                    ddlPublish.Text = listU[0].PUId;
                    txtPCode.Text = listU[0].PCode;
                    txtPName.Text = listU[0].PName;
                    txtPPice.Text = listU[0].PPrice.Split('.')[0];
                    txtSaleOff.Text =(Convert.ToDouble( listU[0].PSaleOff)*Convert.ToDouble(listU[0].PPrice.Split('.')[0])).ToString();
                    txtAuthor.Text = listU[0].PAuthor;
                    ddlStatus.Text = listU[0].PStatus;
                    txtQuantity.Text = listU[0].PNumber;
                    //txtPImg.Text = listU[0].PImg;
                    PDate = listU[0].PCreateDate;
                    lblFile.Text = listU[0].PImg;
                    lblFile2.Text = listU[0].PImg2;
                    PImgEdit.ImageUrl = listU[0].PImg;
                    PImg2Edit.ImageUrl = listU[0].PImg2;
                    chkPActive.Checked = listU[0].PActive == "1" ? true : false;

                    pnUpdate.Visible = true;
                    pnView.Visible = false;

                    break;
                case "Delete":

                    break;
            }
        }
        private void Reset()
        {
            PImgEdit.ImageUrl = "";
            PImg2Edit.ImageUrl = "";
            ddlStatus.Text = "1";
            lblFile.Text = "";
            lblFile2.Text = "";
            txtAuthor.Text = "";
            txtPCode.Text = "";
            txtPName.Text = "";
            txtPPice.Text = "";
            txtSaleOff.Text = "";
            txtQuantity.Text = "";
            chkPActive.Checked = false;
            LoadDropDown();
            ddlCate.SelectedValue = "0";
            ddlPublish.SelectedValue = "0";
        }
        //Add Click
        protected void Add_Click(object sender, EventArgs e)
        {
            Insert = true;
            Reset();
            pnUpdate.Visible = true;
            pnView.Visible = false;
        }
        //Delete Click
        //protected void Delete_Click(object sender, EventArgs e)
        //{
        //    for (int i = 0; i < grdProducts.Items.Count; i++)
        //    {
        //        if (grdProducts.Items[i].ItemType == ListItemType.AlternatingItem || grdProducts.Items[i].ItemType == ListItemType.Item)
        //        {
        //            if (((CheckBox)grdProducts.Items[i].FindControl("chkSelect")).Checked)
        //            {
        //                Business.ProductsService.Products_Delete(grdProducts.Items[i].Cells[1].Text);
        //            }
        //        }
        //    }
        //    BindGird();
        //}
        //Code Save File lên Server
        private string Save(FileUpload file)
        {
            string math = "";
            if (file.FileName != "")
            {
                math = Server.MapPath("/Upload/" + file.FileName);
                file.SaveAs(math);
                return "/Upload/" + file.FileName.ToString();
            }
            else
                return "";
        }
        //Save Click

        protected void Save_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                if (txtAuthor.Text != "" && txtPName.Text != "" && txtPPice.Text != "" && txtQuantity.Text != "0" && txtQuantity.Text != "" && txtSaleOff.Text != "0" && txtSaleOff.Text != "" && ddlCate.SelectedValue != "0" && ddlPublish.SelectedValue != "0")
                {
                    Data.ProductsInfo obj = new Data.ProductsInfo();

                    obj.PId = Id;
                    obj.PCode = txtPCode.Text;
                    obj.PName = txtPName.Text;
                    obj.PPrice = txtPPice.Text;
                    obj.PAuthor = txtAuthor.Text;
                    obj.PSaleOff = ((double)Convert.ToDouble(txtSaleOff.Text) / Convert.ToDouble(txtPPice.Text)).ToString();
                    //obj.PImg = "";

                    obj.PStatus = "1";
                    obj.PUId = ddlPublish.SelectedValue;
                    obj.CatId = ddlCate.SelectedValue;
                    obj.AId = "1";
                    obj.PActive = chkPActive.Checked ? "1" : "0";
                    obj.PNumber = txtQuantity.Text;
                    if (Insert == true)
                    {
                        obj.PCreateDate = DateTime.Now.ToString();
                        obj.PImg = this.Save(filePImg);
                        obj.PImg2 = this.Save(filePImg2);
                        Business.ProductsService.Products_Insert(obj);
                    }
                    else
                    {
                        if (this.Save(filePImg) != "")
                        {
                            obj.PImg = this.Save(filePImg);
                            obj.PImg2 = this.Save(filePImg2);
                        }
                        else
                        {

                            obj.PImg = lblFile.Text;
                            obj.PImg2 = lblFile2.Text;
                        }
                        obj.PCreateDate = PDate;
                        Business.ProductsService.Products_Update(obj);
                    }
                    BindListProduct();

                    pnUpdate.Visible = false;
                    pnView.Visible = true;
                }

                else
                {
                    Flag = false;
                    lblMess.Visible = true;
                    pnUpdate.Visible = true;
                    pnView.Visible = false;
                }
            }
          
        }

        //Back Click
        protected void Back_Click(object sender, EventArgs e)
        {

            pnView.Visible = true;
            pnUpdate.Visible = false;
            BindListProduct();
        }
    }
}